<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="闭包就是能够读取其他函数内部变量的函数 由于在 JavaScript 中，只有函数内部的子函数才能读取局部变量，因此可以把闭包简单理解为 “定义在一个函数内部的函数” 所以，在本质上，闭包就是将函数内部和函数外部连接起来的一座桥梁  简述闭包流程  如果一个函数内部返回了一个函数或多个函数 而返回的函数中具有对自己的外层作用域中的成员的读取或修改 那么称这个函数叫做闭包函数 为什么在外部拿到该函">
<meta property="og:type" content="article">
<meta property="og:title" content="闭包">
<meta property="og:url" content="http://yoursite.com/2017/09/02/闭包/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="闭包就是能够读取其他函数内部变量的函数 由于在 JavaScript 中，只有函数内部的子函数才能读取局部变量，因此可以把闭包简单理解为 “定义在一个函数内部的函数” 所以，在本质上，闭包就是将函数内部和函数外部连接起来的一座桥梁  简述闭包流程  如果一个函数内部返回了一个函数或多个函数 而返回的函数中具有对自己的外层作用域中的成员的读取或修改 那么称这个函数叫做闭包函数 为什么在外部拿到该函">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-09-02T03:59:43.041Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="闭包">
<meta name="twitter:description" content="闭包就是能够读取其他函数内部变量的函数 由于在 JavaScript 中，只有函数内部的子函数才能读取局部变量，因此可以把闭包简单理解为 “定义在一个函数内部的函数” 所以，在本质上，闭包就是将函数内部和函数外部连接起来的一座桥梁  简述闭包流程  如果一个函数内部返回了一个函数或多个函数 而返回的函数中具有对自己的外层作用域中的成员的读取或修改 那么称这个函数叫做闭包函数 为什么在外部拿到该函">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/09/02/闭包/"/>





  <title>闭包 | Hexo</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Hexo</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/09/02/闭包/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="shine-wl">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://dynamic-image.yesky.com/300x-/uploadImages/upload/20140912/upload/201409/wylnwjynkxijpg.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hexo">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">闭包</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-02T11:52:11+08:00">
                2017-09-02
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <ul>
<li>闭包就是能够读取其他函数内部变量的函数</li>
<li>由于在 JavaScript 中，只有函数内部的子函数才能读取局部变量，因此可以把闭包简单理解为 “定义在一个函数内部的函数”</li>
<li>所以，在本质上，闭包就是将函数内部和函数外部连接起来的一座桥梁</li>
</ul>
<p>简述闭包流程</p>
<ol>
<li>如果一个函数内部返回了一个函数或多个函数</li>
<li>而返回的函数中具有对自己的外层作用域中的成员的读取或修改</li>
<li>那么称这个函数叫做闭包函数</li>
<li>为什么在外部拿到该函数就可以访问内层函数的成员？<ul>
<li>原因就在于：函数的作用域链以函数定时时的位置为准</li>
<li>这里就利用函数实现了对内部 foo 变量的读取和修改<a id="more"></a>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line">&lt;script&gt;</div><div class="line">    function fn() &#123;</div><div class="line">      var foo = &apos;bar&apos;</div><div class="line">       var getFoo = function () &#123;</div><div class="line">        return foo</div><div class="line">      &#125;</div><div class="line">      </div><div class="line">      var setFoo = function (val) &#123;</div><div class="line">        foo = val</div><div class="line">      &#125; </div><div class="line">      // 调用函数将setFoo和getFoo以对象的形式进行返回</div><div class="line">      return &#123;</div><div class="line">        getFoo: getFoo,</div><div class="line">        setFoo: setFoo</div><div class="line">      &#125;</div><div class="line">    &#125;</div><div class="line">   </div><div class="line">    var obj = fn()</div><div class="line">    </div><div class="line">    console.log(obj.getFoo()) //bar</div><div class="line">    obj.setFoo(&apos;hello&apos;)</div><div class="line">    console.log(obj.getFoo()) //hello</div><div class="line">  &lt;/script&gt;</div></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ol>
<h4 id="闭包示例"><a href="#闭包示例" class="headerlink" title="闭包示例"></a>闭包示例</h4><ul>
<li>列出如下几个例子方便理解闭包</li>
</ul>
<p>下面是没有用闭包的示例<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">&lt;script&gt;</div><div class="line">    var arr = [10, 20, 30]</div><div class="line">    // for 循环中的 i 是全局变量</div><div class="line">    for (var i = 0; i &lt; arr.length; i++) &#123;</div><div class="line">      arr[i] = function () &#123;</div><div class="line">        console.log(i) // 结果：3个3</div><div class="line">      &#125;</div><div class="line">    &#125;</div><div class="line">&lt;/script&gt;</div></pre></td></tr></table></figure></p>
<p> 用了闭包的示例1—-将i以形参的方式传入到函数里，里面的函数接收，并返回一个函数,里面的i不能被外部修改<br> <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">&lt;script&gt;</div><div class="line">    var arr = [10, 20, 30]</div><div class="line">    // for 循环中的 i 是全局变量</div><div class="line">    for (var i = 0; i &lt; arr.length; i++) &#123;</div><div class="line">      arr[i] = (function (i) &#123;</div><div class="line">      // 将i以形参的方式传入到函数里，里面的函数接收，并返回一个函数</div><div class="line">      // 相当于 var i=i; </div><div class="line">        return function () &#123;</div><div class="line">          console.log(i)</div><div class="line">        &#125;</div><div class="line">      &#125;)(i)</div><div class="line">    &#125;</div><div class="line">    arr.forEach(function (item, index) &#123;</div><div class="line">      item() //1 2 3</div><div class="line">    &#125;)</div><div class="line">&lt;/script&gt;</div></pre></td></tr></table></figure></p>
<p>闭包实例2–定时器永远都会放在普通代码最后执行<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">&lt;script&gt;</div><div class="line">   console.log(111)</div><div class="line"></div><div class="line">   for (var i = 0; i &lt; 3; i++) &#123;</div><div class="line">     // 定时器永远会放到普通代码最后才执行</div><div class="line">     // 哪怕时间为 0</div><div class="line">     // for 循环的时候不会等待定时器的执行，直接就进行下一次循环了</div><div class="line">     setTimeout((function (i) &#123;</div><div class="line">       return function () &#123;</div><div class="line">         console.log(i)</div><div class="line">       &#125;</div><div class="line">     &#125;)(i), 0)</div><div class="line">   &#125;</div><div class="line"></div><div class="line">   console.log(222)</div><div class="line">   // 结果 111 222 0 1 2 </div><div class="line"> &lt;/script&gt;</div></pre></td></tr></table></figure></p>
<p>沙箱模式</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line">&lt;script&gt;</div><div class="line">   ;(function () &#123;</div><div class="line">     // 利用匿名函数自执行保护内部成员不被外部修改或访问</div><div class="line">     var age = 3</div><div class="line">     </div><div class="line">     function F () &#123;</div><div class="line">     &#125;</div><div class="line"></div><div class="line">     F.prototype.getAge = function () &#123;</div><div class="line">       return age</div><div class="line">     &#125;</div><div class="line"></div><div class="line">     F.prototype.setAge = function (val) &#123;</div><div class="line">       if (val &lt; 18) &#123;</div><div class="line">         return console.error(&apos;age 不能小于18岁&apos;)</div><div class="line">       &#125;</div><div class="line">       age = val</div><div class="line">     &#125;</div><div class="line">     window.F = F</div><div class="line">   &#125;)()</div><div class="line"></div><div class="line">   var f = new F()</div><div class="line">   console.log(f.getAge())</div><div class="line"> &lt;/script&gt;</div></pre></td></tr></table></figure>
<p>闭包思考题</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">var name = &quot;The Window&quot;;</div><div class="line"></div><div class="line">  var object = &#123;</div><div class="line">    name: &quot;My Object&quot;,</div><div class="line">    getNameFunc: function () &#123;</div><div class="line">      // 函数内部定义的函数，其 this 指向 window</div><div class="line">      var inner = function () &#123;</div><div class="line">        console.log(this.name) //The Window</div><div class="line">      &#125;</div><div class="line"></div><div class="line">      return inner</div><div class="line">    &#125;</div><div class="line">  &#125;;</div><div class="line">  // 返回 inner在进行调用</div><div class="line">  object.getNameFunc()()</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">var name = &quot;The Window&quot;;　　</div><div class="line">   var object = &#123;　　　　</div><div class="line">     name: &quot;My Object&quot;,</div><div class="line">     getNameFunc: function () &#123;</div><div class="line">       var that = this;</div><div class="line">       // 定义一个变量接收 this</div><div class="line">       // 其它成员，按照定义时所处的作用域环境沿着作用域链查找</div><div class="line">       return function () &#123;</div><div class="line">         return that.name;</div><div class="line">       &#125;;</div><div class="line">     &#125;</div><div class="line">   &#125;;</div><div class="line"></div><div class="line">   console.log(object.getNameFunc()()) //My Object</div></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/31/canvas案例/" rel="next" title="canvas案例">
                <i class="fa fa-chevron-left"></i> canvas案例
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/02/递归/" rel="prev" title="递归">
                递归 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://dynamic-image.yesky.com/300x-/uploadImages/upload/20140912/upload/201409/wylnwjynkxijpg.jpg"
               alt="shine-wl" />
          <p class="site-author-name" itemprop="name">shine-wl</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives/">
            
                <span class="site-state-item-count">21</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#闭包示例"><span class="nav-number">1.</span> <span class="nav-text">闭包示例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">shine-wl</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动</div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">主题 &mdash; <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.2</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  





  

  

  

  

  

  

</body>
</html>
